import numpy as np
from scipy.interpolate import griddata
from typing import Dict, Tuple, List
import struct
import zipfile


def parse_radar_data(zip_file_path: str) -> Dict:
    """解析雷达多层格点数据文件（保持原函数不变）"""
    with zipfile.ZipFile(zip_file_path, 'r') as zf:
        dat_filename = zf.namelist()[0]
        with zf.open(dat_filename, 'r') as f:
            binary_data = f.read()

    offset = 0  # 偏移量指针
    parsed = {}

    # 解析文件头固定部分
    magic, = struct.unpack_from('<2s', binary_data, offset)
    parsed['magic'] = magic.decode()
    offset += 2
    if parsed['magic'] != '**':
        raise ValueError("文件格式错误，不是有效的格点数据文件")

    version, = struct.unpack_from('<4s', binary_data, offset)
    parsed['version'] = version.decode()
    offset += 4

    lon_lat = struct.unpack_from('<8f', binary_data, offset)
    parsed['corners'] = [
        (lon_lat[0], lon_lat[1]),  # 左上角
        (lon_lat[2], lon_lat[3]),  # 右上角
        (lon_lat[4], lon_lat[5]),  # 右下角
        (lon_lat[6], lon_lat[7])  # 左下角
    ]
    offset += 8 * 4

    H, L = struct.unpack_from('<2h', binary_data, offset)
    parsed['H'] = H  # 横向格点数量
    parsed['L'] = L  # 纵向格点数量
    offset += 2 * 2

    grid_size, = struct.unpack_from('<f', binary_data, offset)
    parsed['grid_size_km'] = grid_size
    offset += 4

    N, = struct.unpack_from('<h', binary_data, offset)
    parsed['N'] = N  # 垂直层数
    offset += 2

    # 解析动态部分（每层高度）
    heights = struct.unpack_from(f'<{N}f', binary_data, offset)
    parsed['layer_heights'] = heights
    offset += N * 4

    # 解析投影模式和保留字段
    proj_mode, res1, res2, res3 = struct.unpack_from('<4B', binary_data, offset)
    parsed['proj_mode'] = {0: '墨卡托', 1: '等距离'}.get(proj_mode, '未知')
    parsed['reserved'] = (res1, res2, res3)
    offset += 4

    # 解析数据体
    data_size = H * L * N
    data_flat = struct.unpack_from(f'<{data_size}f', binary_data, offset)

    # 重塑为三维数组：(层数, 纬度格点, 经度格点)
    parsed['data'] = [
        [
            data_flat[layer * L * H + row * H: layer * L * H + (row + 1) * H]
            for row in range(L)
        ]
        for layer in range(N)
    ]

    return parsed